<template>
  <el-row justify="space-between">
    <!-- 搜索栏-->
    <el-col :span="10">
      <el-input
          v-model="cusName"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter="search"
      >
      </el-input>
    </el-col>

    <el-col :span="10">
      <el-input
          v-model="city"
          placeholder="请输入城市"
          clearable
          @keyup.enter="search"
      ></el-input>
    </el-col>

    <!-- 搜索按钮 -->
    <el-col :span="2">
      <el-button type="primary" icon="el-icon-search" @click="search" class="search-button">搜索</el-button>
    </el-col>
    <!--新增按钮-->
    <el-col :span="2">
      <el-button type="primary" @click="openAddDialog">
        <el-icon>
          <Plus/>
        </el-icon>
        新增客户
      </el-button>
    </el-col>
  </el-row>

  <!--表格-->
  <MessageBox2 :page-size="pageSize" :current-page="currentPage" :total="total" :table-data="customerStore.customers"
               :table-title-list="tableTitleList" :loading="loading" :table-title="tableTitle" :batch-mode="batchMode"
               @current-change="currentPageChange" @size-change="pageSizeChange" @selectionChange="updateSelectedRows">
    <template #title-btn>
      <el-button type="primary" @click="toggleBatchMode">
        {{ batchMode ? "取消批量操作" : "批量操作" }}
      </el-button>
      <el-button
          type="danger"
          :disabled="!selectedRows.length"
          @click="handleBatchDelete"
          v-if="batchMode"
      >
        批量删除
      </el-button>
    </template>

    <template v-slot:table-btn>
      <el-table-column label="操作">
        <template #default="{row}">
          <el-button icon="edit" circle plain type="warning" size="mini" @click="openEditDialog(row)">编辑</el-button>
          <el-button icon="delete" circle plain type="danger" size="mini" @click="deleteCustomer(row.cusId)">删除
          </el-button>
        </template>
      </el-table-column>
    </template>
  </MessageBox2>

  <!-- 新增对话框 -->
  <el-dialog title="新增客户" v-model="addDialogVisible" width="30%">
    <el-form :model="newCustomer" label-width="100px">
      <el-form-item label="客户姓名" prop="cusName" required>
        <el-input v-model="newCustomer.cusName" placeholder="请输入客户姓名"></el-input>
      </el-form-item>
      <el-form-item label="联系人姓名" prop="contactName" required>
        <el-input v-model="newCustomer.contactName" placeholder="请输入客户联系人姓名"></el-input>
      </el-form-item>

      <el-form-item label="联系人职位" prop="contactTitle">
        <el-input v-model="newCustomer.contactTitle" placeholder="请输入客户联系人职位"></el-input>
      </el-form-item>

      <el-form-item label="联系电话" prop="phone" required>
        <el-input v-model="newCustomer.phone" placeholder="请输入联系人电话"></el-input>
      </el-form-item>

      <el-form-item label="地址" prop="address">
        <el-input v-model="newCustomer.address" placeholder="请输入地址"></el-input>
      </el-form-item>

      <el-form-item label="城市" prop="city">
        <el-input v-model="newCustomer.city" placeholder="请输入城市"></el-input>
      </el-form-item>

      <el-form-item label="地区" prop="region">
        <el-input v-model="newCustomer.region" placeholder="请输入地区"></el-input>
      </el-form-item>
      <el-form-item label="邮政编码" prop="postalCode">
        <el-input v-model="newCustomer.postalCode" placeholder="请输入邮政编码"></el-input>
      </el-form-item>
      <el-form-item label="国家" prop="country">
        <el-input v-model="newCustomer.country" placeholder="请输入国家"></el-input>
      </el-form-item>
      <el-form-item label="传真号码" prop="fax">
        <el-input v-model="newCustomer.fax" placeholder="请输入传真号码"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="addDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="saveCustomer">保存</el-button>
    </template>
  </el-dialog>

  <!--修改对话框-->
  <el-dialog title="编辑客户" v-model="editDialogVisible" width="30%">
    <el-form :model="editData" label-width="100px">
      <el-form-item label="客户姓名" prop="cusId">
        <el-input v-model="editData.cusName" disabled></el-input>
      </el-form-item>
      <el-form-item label="联系人姓名" prop="contactName">
        <el-input v-model="editData.contactName"></el-input>
      </el-form-item>
      <el-form-item label="联系人职位" prop="contactTitle">
        <el-input v-model="editData.contactTitle"></el-input>
      </el-form-item>
      <el-form-item label="联系电话" prop="phone">
        <el-input v-model="editData.phone"></el-input>
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-input v-model="editData.address"></el-input>
      </el-form-item>
      <el-form-item label="城市" prop="city">
        <el-input v-model="editData.city"></el-input>
      </el-form-item>
      <el-form-item label="地区" prop="region">
        <el-input v-model="editData.region"></el-input>
      </el-form-item>
      <el-form-item label="邮政编码" prop="postalCode">
        <el-input v-model="editData.postalCode"></el-input>
      </el-form-item>
      <el-form-item label="国家" prop="country">
        <el-input v-model="editData.country"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="editDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="editCustomer" :loading="isSaving">保存</el-button>
    </template>
  </el-dialog>
</template>
<script setup>
import {reactive, ref, toRaw} from 'vue'
import MessageBox2 from "@/components/MessageBox2.vue";
import {customersStore} from "@/stores/modules/customers"
import {
  addCustomerService,
  deleteCustomerService,
  getCustomerCountService,
  getCustomerPageService,
  updateCustomerService
} from "@/api/customer"
import {ElMessage} from "element-plus";

// 获取store 数据
const customerStore = customersStore()


// 表格参数
const tableTitle = "客户信息"
const tableTitleList = {
  cusId: '客户编号',
  cusName: '客户名称',
  contactName: '联系人',
  contactTitle: '联系人职务',
  phone: '电话号码',
  address: '地址',
  city: '城市',
  region: '地区',
  postalCode: '邮政编码',
  country: '国家',
  fax: '传真号码'
}
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const cusName = ref('')
const city = ref('')


//页面变化 + 条件变化
const getCustomerPage = async (currentPage, pageSize, cusName, city) => {
  loading.value = true

  console.log(currentPage, pageSize, cusName, city)
  try {
    const res = await getCustomerPageService(currentPage.value, pageSize.value, cusName.value, city.value)
    if (res.status === 200) {
      customerStore.setCustomers(res.data.data.records)
      total.value = res.data.data.total
    }
  } catch (e) {
    ElMessage.error('请求出错')
    console.log(e)
  } finally {
    loading.value = false
  }

}

// 查询函数
const search = () => {
  getCustomerPage(currentPage, pageSize, cusName, city)
}

//子组件触发
const currentPageChange = (cP) => {
  currentPage.value = cP
  getCustomerPage(currentPage, pageSize, cusName, city)
}
const pageSizeChange = (size) => {
  pageSize.value = size
  getCustomerPage(currentPage, pageSize, cusName, city)
}

// 获取客户总数
const getCustomerCount = async () => {
  try {
    const res = await getCustomerCountService()
    if (res.status === 200) {
      total.value = res.data.data
    }
  } catch (e) {
    ElMessage.error('请求出错')
    console.log(e)
  }
}

// 新增客户信息
const addDialogVisible = ref(false)
const newCustomer = reactive({
  cusName: '',
  contactName: '',
  contactTitle: '',
  phone: '',
  address: '',
  city: '',
  region: '',
  postalCode: '',
  country: '',
  fax: ''
})

// 新增客户
const openAddDialog = () => {
  addDialogVisible.value = true
}

const saveCustomer = async () => {
  try {
    const res = await addCustomerService(newCustomer)
    console.log(res)
    if (res.status === 200) {
      ElMessage.success('新增客户成功')
      await getCustomerPage(currentPage, pageSize, cusName, city)
      addDialogVisible.value = false
    } else {
      ElMessage.error('新增失败')
    }
  } catch (e) {
    ElMessage.error('请求出错')
    console.log(e)
  }
}

//编辑客户
const editDialogVisible = ref(false)
const editData = ref({})
const isSaving = ref(false); // 用于保存按钮的加载状态
const openEditDialog = (row) => {
  // console.log("row")
  editData.value = {...row}
  // console.log(editData)
  editDialogVisible.value = true
}
const editCustomer = async () => {
  try {
    isSaving.value = true;
    const res = await updateCustomerService(toRaw(editData.value))
    if (res.status === 200) {
      ElMessage.success('编辑客户成功')
      await getCustomerPage(currentPage, pageSize, cusName, city)
      editDialogVisible.value = false
    } else {
      ElMessage.error('编辑失败')
    }
  } catch (e) {
    ElMessage.error('请求出错')
    console.log(e)
  } finally {
    isSaving.value = false;
  }

}

// 删除客户
// 状态控制
const batchMode = ref(false); // 是否启用批量模式
const selectedRows = ref([]); // 存储选中的行数据
// 切换批量操作模式
const toggleBatchMode = () => {
  batchMode.value = !batchMode.value;
  if (!batchMode.value) {
    selectedRows.value = []; // 清空选中数据
  }
};
// 更新选中的行数据
const updateSelectedRows = (rows) => {
  selectedRows.value = rows;
};
// 批量删除逻辑
const handleBatchDelete = async () => {
  const ids = selectedRows.value.map((row) => row.cusId);
  try {
    const res = await deleteCustomerService(ids);
    if (res.status === 200) {
      customerStore.customers = customerStore.customers.filter(
          (item) => !ids.includes(item.cusId)
      );
      toggleBatchMode();
    }
  } catch (error) {
    console.error(error);
  }
  getCustomerPage(currentPage, pageSize, cusName, city)
};
const deleteCustomer = async (id) => {
  const res = await deleteCustomerService(id)
  if (res.status === 200) {
    customerStore.customers = customerStore.customers.filter(item => item.cusId !== id)
    ElMessage.success('删除成功')
  }
  getCustomerPage(currentPage, pageSize, cusName, city)
}

// 初始化
console.log("初始化")
getCustomerCount()
getCustomerPage(currentPage, pageSize, cusName, city)
console.log("初始化结束")
</script>

<style scoped>
.search-button {
  width: 100%;
}
</style>